package com.woniuxy.shop.servelet.manager;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.shop.entity.CateGory;
import com.woniuxy.shop.entity.Goods;
import com.woniuxy.shop.entity.PageBean;
import com.woniuxy.shop.exception.SameGoodException;
import com.woniuxy.shop.exception.ServiceException;
import com.woniuxy.shop.service.CateGoryService;
import com.woniuxy.shop.service.GoodsService;
import com.woniuxy.shop.service.ServiceProxyFactory;
import com.woniuxy.shop.utils.ShopUtils;

/**
 * Servlet implementation class CateGoryServelet
 */
@WebServlet("/manager/GoodsServelet")
@MultipartConfig
public class GoodServelet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	CateGoryService cgs = ServiceProxyFactory.getProxy(CateGoryService.class);
	GoodsService gs = ServiceProxyFactory.getProxy(GoodsService.class);

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");// 获取参数前指定编码
		String opr = request.getParameter("opr");
		if ("initgoods".equals(opr)) {
			doInitGoods(request, response);
		} else if ("add".equals(opr)) {
			doAdd(request, response);
		} else if ("query".equals(opr)) {
			doQuery(request, response);
		} else if ("del".equals(opr)) {
			doDel(request, response);
		} else if ("downshop".equals(opr)) {
			doDownshop(request, response);
		} else if ("initUpdate".equals(opr)) {
			doInintUpdate(request, response);
		} else if ("update".equals(opr)) {
			doUpdate(request, response);
		}
	}

	private void doUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String hidimg = request.getParameter("hidimg");
		String name = request.getParameter("upname");
		int id = Integer.parseInt(request.getParameter("id"));
		if (name == null || name.trim().equals("")) {
			request.setAttribute("msg", "商品名不能为空");
			request.getRequestDispatcher("GoodsServelet?opr=initUpdate").forward(request, response);
			return;
		}

		if (name.length() > 50) {
			request.setAttribute("msg", "商品名长度不能超过10位");
			request.getRequestDispatcher("GoodsServelet?opr=initUpdate").forward(request, response);
			return;
		}

		int categoryid = Integer.parseInt(request.getParameter("choosecategory"));

		int stock = Integer.parseInt(request.getParameter("stock"));
		if (stock < 0) {
			request.setAttribute("msg2", "库存不能为负数");
			request.getRequestDispatcher("GoodsServelet?opr=initUpdate").forward(request, response);
			return;
		}

		double marketprice = Double.parseDouble(request.getParameter("marketprice"));
		if (marketprice < 0) {
			request.setAttribute("msg3", "市场价不能为负数");
			request.getRequestDispatcher("GoodsServelet?opr=initUpdate").forward(request, response);
			return;
		}

		double saleprice = Double.parseDouble(request.getParameter("saleprice"));
		if (saleprice < 0) {
			request.setAttribute("msg4", "售价不能为负数");
			request.getRequestDispatcher("GoodsServelet?opr=initUpdate").forward(request, response);
			return;
		}

		String image;
		Part part = request.getPart("image");
		long size = part.getSize();
		if (size == 0) {
			image = hidimg; // 如果没有上传图片就用原有的图片
		} else {
			String path = getServletContext().getRealPath("/manager/images/goods");
			// 产生一个唯一的文件名
			String fileName = UUID.randomUUID().toString().replaceAll("-", "");
			part.write(path + "/" + fileName);
			System.out.println(path);
			image = "images/goods/" + fileName;
		}

		String content = request.getParameter("content");

		Goods goods = new Goods();
		goods.setId(id);
		goods.setDescription(content);
		goods.setCategoryid(categoryid);
		goods.setName(name);
		goods.setImage(image);
		goods.setMarketprice(marketprice);
		goods.setSaleprice(saleprice);
		goods.setStatus("正常");
		goods.setStock(stock);

		try {
			gs.updateGoods(goods);
		} catch (ServiceException e) {
			if (e.getCause() instanceof SameGoodException) {
				request.setAttribute("msg", "商品" + name + "已被添加");
			} else {
				request.setAttribute("msg", "系统维护中，请稍后再试");
			}
			request.getRequestDispatcher("GoodsServelet?opr=initUpdate").forward(request, response);
			return;
		}
		request.setAttribute("update", "商品《" + name + "》修改成功！");
		request.getRequestDispatcher("GoodsServelet?opr=query").forward(request, response);

	}

	/**
	 * 将ID
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void doInintUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Goods g;
		List<CateGory> categories;
		try {
			int id = Integer.parseInt(request.getParameter("id"));
			g = gs.getGoods(id);
			categories = cgs.getCateGory();
		} catch (ServiceException e) {
			request.setAttribute("updateerror", "系统维护中，请稍后再试");
			request.getRequestDispatcher("goods/goods_list.jsp").forward(request, response);
			return;
		}
		request.setAttribute("goods", g);
		request.setAttribute("categories", categories);
		request.getRequestDispatcher("goods/goods_update.jsp").forward(request, response);

	}

	private void doDownshop(HttpServletRequest request, HttpServletResponse response) throws IOException {

		String data = request.getParameter("data");
		String type = request.getParameter("type");
		String[] nums = data.split(",");
		for (int i = 0; i < nums.length; i++) {
			try {
				gs.updataStatus(Integer.parseInt(nums[i]), type);
			} catch (ServiceException e) {
				// TODO: handle exception
			}
		}
		response.sendRedirect("GoodsServelet?opr=query");

	}

	private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String name = request.getParameter("gname");
		try {
			gs.delete(Integer.parseInt(id));// 被引用的商品删除不了，待改善
		} catch (ServiceException e) {
			request.setAttribute("error", "系统维护中，请稍后再试");
			request.getRequestDispatcher("GoodsServelet?opr=query").forward(request, response);
			return;
		}
		request.setAttribute("success", name + "删除成功");
		request.getRequestDispatcher("GoodsServelet?opr=query").forward(request, response);
	}

	private void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int page = 1;
		String name = request.getParameter("name");
		String categoryid = request.getParameter("categoryid");
		String status = request.getParameter("status");
		String minstock = request.getParameter("minstock");
		String maxstock = request.getParameter("maxstock");
		String nowpage = request.getParameter("nowpage");
		if (!ShopUtils.isEmpty(nowpage)) {
			try {
				page = Integer.parseInt(nowpage);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		Goods g = new Goods();
		if (!ShopUtils.isEmpty(name)) {
			g.setName(name);
		}

		if (!ShopUtils.isEmpty(categoryid)) {
			g.setCategoryid(Integer.parseInt(categoryid));
		}
		if (!ShopUtils.isEmpty(status)) {
			g.setStatus(status);
		}
		if (!ShopUtils.isEmpty(minstock)) {
			try {
				g.setMinstock(Integer.parseInt(minstock));
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		if (!ShopUtils.isEmpty(maxstock)) {
			try {
				g.setMaxstock(Integer.parseInt(maxstock));
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		String p = request.getParameter("page");
		if (p != null) {
			page = Integer.parseInt(p);
		}

		PageBean<Goods> pb = gs.getPageBean(page, g, 5);
		List<CateGory> categories = cgs.getCateGory();
		request.setAttribute("pb", pb);
		request.setAttribute("categories", categories);
		request.setAttribute("goods", g);
		request.getRequestDispatcher("goods/goods_list.jsp").forward(request, response);
	}

	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String name = request.getParameter("name");
		if (name == null || name.trim().equals("")) {
			request.setAttribute("msg", "商品名不能为空");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}

		if (name.length() > 50) {
			request.setAttribute("msg", "商品名长度不能超过10位");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}

		int categoryid = Integer.parseInt(request.getParameter("choosecategory"));

		int stock = Integer.parseInt(request.getParameter("stock"));
		if (stock < 0) {
			request.setAttribute("msg2", "库存不能为负数");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}

		double marketprice = Double.parseDouble(request.getParameter("marketprice"));
		if (marketprice < 0) {
			request.setAttribute("msg3", "市场价不能为负数");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}

		double saleprice = Double.parseDouble(request.getParameter("saleprice"));
		if (saleprice < 0) {
			request.setAttribute("msg4", "售价不能为负数");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}

		Part part = request.getPart("image");
		String imgname = part.getName();
		if (imgname.equals("")) {
			request.setAttribute("msg5", "不能上传空文件");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}
		// 取得Tomcat的绝对路径
		String path = getServletContext().getRealPath("manager/images/goods");
		// 产生一个唯一的文件名
		String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		part.write(path + "/" + fileName);
		String image = "images/goods/" + fileName;
		String content = request.getParameter("content");

		Goods goods = new Goods();
		goods.setDescription(content);
		goods.setCategoryid(categoryid);
		goods.setName(name);
		goods.setImage(image);
		goods.setMarketprice(marketprice);
		goods.setSaleprice(saleprice);
		goods.setStatus("正常");
		goods.setStock(stock);

		try {
			gs.add(goods);
		} catch (ServiceException e) {
			if (e.getCause() instanceof SameGoodException) {
				request.setAttribute("msg", "商品" + name + "已被添加");
			} else {
				request.setAttribute("msg", "系统维护中，请稍后再试");
			}
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}
		request.setAttribute("success", "商品《" + name + "》添加成功！");
		request.getRequestDispatcher("GoodsServelet?opr=initgoods").forward(request, response);
		;
	}

	private void doInitGoods(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<CateGory> categories = cgs.getCateGory();
		if (categories.size() == 0) {
			request.setAttribute("nocategory", "皇上，您还没有商品类别可用，是否前往添加？");
			request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
			return;
		}
		request.setAttribute("categories", categories);
		request.getRequestDispatcher("goods/goods_add.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
